package com.zm.demo.ws.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zm.demo.webservice.server.dto.DataExchange;
import com.zm.demo.webservice.server.dto.UserDTO;
import org.apache.cxf.transport.commons_text.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2020/2/24.
 */
public class Main {

    public static String doThirdRequestWithHeader(String url, String mapXml, String requestMethod, Integer timeOut, String soapAction){
        HttpURLConnection http = null;
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        try {
            URL tourl = new URL(url);
            http = (HttpURLConnection) tourl.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod(requestMethod);
            if (timeOut != null && timeOut>0){
                http.setConnectTimeout(timeOut);
                http.setReadTimeout(timeOut);
            }

            http.setRequestProperty("Content-Type", "text/xml;charset=UTF-8" );
            http.setRequestProperty("SOAPAction", soapAction );
            http.connect();

            StringBuilder xml= new StringBuilder();
            xml.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:"+ soapAction +" xmlns:ns2=\"http://server.webservice.demo.zm.com/\">")
                .append(mapXml)
                .append("</ns2:" + soapAction + "></soap:Body></soap:Envelope>");

            out = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
            out.append(xml);
            out.flush();

            if (http.getResponseCode() != HttpURLConnection.HTTP_OK){
//                LOGGER.error("P3|ERROR|ERROR|ERROR|request error, url is {}, responseCode is {}, error message is {}",
//                        url, http.getResponseCode(), http.getResponseMessage());
                throw new IllegalStateException(http.getResponseCode()+"");
            }

            reader = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));

            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String bufferStr = buffer.toString();
            return bufferStr.substring(bufferStr.indexOf("<return>"), bufferStr.indexOf("</return>")+9);
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            try {
                if (http != null){
                    http.disconnect();
                }
                if (out != null){
                    out.close();
                }                if (reader != null){
                    reader.close();
                }
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 使用SOAP1.1发送消息
     *
     * @param postUrl
     * @param mapXml
     * @param soapAction
     * @return
     */
    public static String doPostSoap1_1(String postUrl, String mapXml,
                                       String soapAction) {
        String retStr = "";
        String xml = "";
        // 创建HttpClientBuilder
        HttpClientBuilder
                httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        //  设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout( 3000 )
                .setConnectTimeout( 3000 ).build();
        httpPost.setConfig(requestConfig);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8" );
            httpPost.setHeader("SOAPAction", soapAction );

            xml += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:"+ soapAction +" xmlns:ns2=\"http://server.webservice.demo.zm.com/\">";
            xml += mapXml;
            xml += "</ns2:" + soapAction + "></soap:Body></soap:Envelope>";
            System.out.println(xml);

            StringEntity data = new StringEntity( xml, Charset.forName("UTF-8") );
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient
                    .execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            System.out.println("exception in doPostSoap1_1" + e);
        }

        retStr = retStr.substring( retStr.indexOf("<return>"), retStr.indexOf("</return>") + 9);
//        retStr = StringEscapeUtils.unescapeHtml( retStr );
        return retStr;
    }


    public final static String POST_URL = "http://localhost:9000/helloWorld?wsdl";

    public static void main(String[] args) throws Exception{

//        //多参字符串xml请求
//        String pre_id = "1009022100";
//        String ter_id = "小票机";
//        String card_id = "6217002020036666666";
//        Map<String, Object> param = new HashMap<>();
//        param.put( "name", "namename" );
////        param.put( "ter_id", ter_id );
////        param.put( "card_id", card_id );
//
//        String msg = doPostSoap1_1( POST_URL, param, "sayHello" );
//        System.out.println(msg);

        //一参xml格式请求
        UserDTO userDTO = new UserDTO();
        userDTO.setName("zzzz");
        userDTO.setAge(12234);
        UserDTO userDTO1 = new UserDTO();
        userDTO1.setName("zzzz1");
        userDTO1.setAge(1223411);

        UserDTO userDTO2 = new UserDTO();
        userDTO2.setName("zzzz1");
        userDTO2.setAge(1223411);
        userDTO2.setUserDTOList(Arrays.asList(userDTO, userDTO1));


        JSONObject map = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(JSONObject.parseObject(JSONObject.toJSONString(userDTO)));
        jsonArray.add(JSONObject.parseObject(JSONObject.toJSONString(userDTO1)));
        map.put("arg0", JSONObject.parseObject(JSONObject.toJSONString(userDTO2)));
        //把对象转化为 XML,并且设置别名
        String xml = DataExchange.json2xml(map.toJSONString());
//        String xml = JsonXmlUtils.JsonToXml(map);
        Map param = new HashMap<>();
        //把对象转化为 XML,并且设置别名
//        String msg = doPostSoap1_1( POST_URL, xml, "getUser1" );

        String msg= doThirdRequestWithHeader(POST_URL, xml, "POST", 10000,  "getUser1");
        System.out.println(msg);
        System.out.println(JSONObject.parseObject(DataExchange.xml2json(msg)).get("return"));
    }

}
